#include <map>
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <cstring>
#include <cstdlib>
#include <algorithm>

using namespace std;

const int MAXN=2005;

map<string, int> mp;
vector<string> st;
vector<int> A[MAXN];
int dp[MAXN][MAXN];
char P[MAXN], start[10];
int K, N, cnt;

int calc(string st, int j)
{
	for (int i=0; i<st.size()&&j<N; i++)
		if (st[i]==P[j]) j++;
	return j;
}

int solve(int id, int j)
{
	if (dp[id][j]!=-1) return dp[id][j];
	if (A[id].size()==1) return dp[id][j]=calc(st[A[id][0]], j);
	else return dp[id][j]=solve(A[id][1], solve(A[id][0], j));
}

int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%d\n", &K); cnt=0; mp.clear(); st.clear();
		for (int i=0; i<3*K; i++) A[i].clear();
		for (int i=0; i<K; i++)
		{
			char buff[100];
			char s1[10], s2[10], s3[10];
			int o1, o2, o3;
			gets(buff);
			if (strchr(buff, '+')!=NULL)
			{
				sscanf(buff, "%s = %s + %s", s1, s2, s3);
				if (mp.find(s1)==mp.end()) o1=cnt, mp[s1]=cnt++, st.push_back(s1);
				else o1=mp[s1];
				if (mp.find(s2)==mp.end()) o2=cnt, mp[s2]=cnt++, st.push_back(s2);
				else o2=mp[s2];
				if (mp.find(s3)==mp.end()) o3=cnt, mp[s3]=cnt++, st.push_back(s3);
				else o3=mp[s3];
				A[o1].push_back(o2); A[o1].push_back(o3);
			}
			else
			{
				sscanf(buff, "%s = %s", s1, s2);
				if (mp.find(s1)==mp.end()) o1=cnt, mp[s1]=cnt++, st.push_back(s1);
				else o1=mp[s1];
				if (mp.find(s2)==mp.end()) o2=cnt, mp[s2]=cnt++, st.push_back(s2);
				else o2=mp[s2];
				A[o1].push_back(o2);
			}
		}
		scanf("%s%s", start, P);
		int o=mp[start];
		N=strlen(P);
		memset(dp, -1, sizeof(dp));
		solve(o, 0);
		if (dp[o][0]>=N) puts("YES");
		else puts("NO");
	}
	return 0;
}
